import {
  findUserNotArchiveProjectsReq,
  switchProjectReq
} from '@/service/modules/project'
import { getUserInfoReq, logoutReq } from '@/service/modules/user'
import { getUnreadCountReq } from '@/service/modules/message'
import { useAsyncState } from '@vueuse/core'
import { reactive, Ref } from 'vue'
import { UserInfo } from '@/service/modules/user/types'
import type { Response } from '@/service/modules/common/types'
import { useUserStore } from '@/store/user/user'

export function useHeader() {
  const variables = reactive({
    projectOptions: [],
    unreadCount: 0
  })

  //获取项目下拉选项
  const getProjectOptions = (params: any) => {
    const { state } = useAsyncState(
      findUserNotArchiveProjectsReq(params).then((res: { data: any[] }) => {
        variables.projectOptions = res.data.map(
          (item): { label: string; value: number } => {
            return {
              label: item.name,
              value: item.id
            }
          }
        ) as any
      }),
      {}
    )
    return state
  }

  //切换项目
  const switchProject = async (id: number) => {
    const params = { proId: id }
    await switchProjectReq(params)
    //更新用户信息缓存
    const userInfoRes: Response<UserInfo> = await getUserInfoReq()
    window.$store.commit('updateUserInfo', userInfoRes.data)
    useUserStore().setUserInfo(userInfoRes.data)
    window.$store.commit('clearTabPanes')
    window.$router.push({
      path: '/home',
      query: {
        tab: window.$t('common.home'),
        tabName: 'HomeTab'
      }
    })
  }

  //获取未读消息数量
  const getUnreadCount = () => {
    const { state } = useAsyncState(
      getUnreadCountReq().then((res: { data: null }) => {
        variables.unreadCount = res.data as any
      }),
      {}
    )
    return state
  }

  //用户退出登录
  const logout = async (token: string) => {
    const params = { access_token: token }
    await logoutReq(params)
  }
  return { variables, getProjectOptions, switchProject, getUnreadCount, logout }
}
